import uuid;
from optparse import OptionParser, OptionGroup;


def getOptionParser():
    usage = "Usage: %prog\n" \
    " -u convert time based uuid to 31 string.        exp: -u 1caf87e0-6d11-11ec-95f9-bd01b071fe43 \n" \
    " -s convert 31 string to time based uuid.        exp: -s 1ec6d111caf87e095f9bd01b071fe43\n" \
    " -f generate How many time based uuid.           exp: -f 5\n" \
    " -g generate How many 31 lens time based string. exp: -g 5\n"
    parser = OptionParser(usage=usage)
    prodEnvOptionGroup = OptionGroup(parser, "Product Env Options", 
    "Normal user use these options switch tools, Make sure these options are can be used together")

    prodEnvOptionGroup.add_option("-u", "--fromUUIDTo31String", action="store_true", help="UUID of these")
    prodEnvOptionGroup.add_option("-s", "--from31StringToUUID", action="store_true", help="Use string")
    prodEnvOptionGroup.add_option("-f", "--generate_uuid", action="store", dest="manyUUID", help="Generate timebase UUID")
    prodEnvOptionGroup.add_option("-g", "--generate_string", action="store", dest="manyString", help="Generate 31 UUID string based on time")
    
    parser.add_option_group(prodEnvOptionGroup)
    return parser

def generate_uuid(uuid_str):
    return uuid.UUID("{UUID_STR}".format(UUID_STR=uuid_str))


def str31_to_uuid36(uuid_str):
    return uuid_str[7:15] + "-" + uuid_str[3:7] + "-1" + uuid_str[0: 3] + "-" + uuid_str[15: 19] + "-" + uuid_str[19:]


def fromString(uuid_str):
    return generate_uuid(str31_to_uuid36(uuid_str))


def fromTimeUUID(time_uuid_str):
    return time_uuid_str[15: 18] + time_uuid_str[9: 13] + time_uuid_str[0: 8] + time_uuid_str[19: 23] + time_uuid_str[24:]


def time_based_uuid():
    return uuid.uuid1()


def time_based_string():
    return fromTimeUUID(str(time_based_uuid()))


def generate(many, f):
    for i in range(0, int(many)):
        print(f())


def fetch_src_str(args):
    try: 
        return args[0]
    except IndexError:
        print(parser.get_usage())
        exit(1)


def validate_generator_many(many):
    try:
        int(many)
    except TypeError:
        print(parser.get_usage())
        exit(1)


def is_non_options(options):
    for key in options.__dict__.keys():
        if options.__dict__[key] is not None:
            return False
    return True


def judge_output_usage(options, args):
    if len(args) == 0 and is_non_options(options):
        print(parser.get_usage())
        exit(0)


if __name__ == "__main__":
    parser = getOptionParser()
    options, args = parser.parse_args()
    # print("options:", options)
    # print("args:", args)
    
    judge_output_usage(options, args)

    result = ""
    try:
        if options.fromUUIDTo31String == True:
            src_str = fetch_src_str(args)
            result = fromTimeUUID(src_str)
        elif options.from31StringToUUID == True:
            src_str = fetch_src_str(args)
            result = fromString(src_str)
        elif options.manyUUID:
            validate_generator_many(options.manyUUID)
            generate(options.manyUUID, time_based_uuid)
        elif options.manyString:
            validate_generator_many(options.manyString)
            generate(options.manyString, time_based_string)
    except Exception as e:
        result = str(e) + "\n" + parser.get_usage()

    print(result)

